package com.gotrade.springbootexceptiondemo.common;

import com.gotrade.springbootexceptiondemo.common.enums.ResultCode;
import com.gotrade.springbootexceptiondemo.exception.ApiException;
import com.gotrade.springbootexceptiondemo.model.Result;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.servlet.http.HttpServletRequest;

/**
 * @author jason.tang
 * @create 2019/4/28
 * @description 全局异常处理
 */

@RestControllerAdvice
@ResponseBody
public class GlobalExceptionHandler {

    /**
     * Catch Others Exception
     * @param request
     * @param ex
     * @return
     */
    @ExceptionHandler(Exception.class)
    public Result<?> globalException(HttpServletRequest request, Throwable ex) {
        Result<String> rst = Result.failure(ResultCode.SYSTEM_ERROR);
        rst.setMessage(ex.getMessage());
        return rst;
    }

    /**
     * 捕获自定义异常信息
     * @param request
     * @param exception
     * @return
     */
    @ExceptionHandler(value = ApiException.class)
    public Result<?> apiException(HttpServletRequest request, ApiException exception) {
        // 获取错误码
        ResultCode resultCode = exception.getResultCode();
        // 获取数据信息
        Object data = exception.getData();

        // 根据条件返回不同的错误信息
        Result<?> rst = null;
        if (resultCode != null) {
            if (data != null) {
                rst = Result.failure(resultCode, data);
            } else {
                rst = Result.failure(resultCode);
            }
        } else {
            rst = Result.failure(ResultCode.SYSTEM_ERROR);
        }
        return rst;
    }
}
